package com.jnc.rest.biz.common.controller;

import com.jnc.rest.util.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @Auther: jjn
 * @Date: 2020/4/24 11:19
 * @Desc: 通用controller 类
 */
@Slf4j
@RestController
public class CommonController {

    /**
     * 通用下载接口
     * @param filePath 文件路径
     * @param fileName 文件名称
     * @param del  是否下载后删除，true:删除；false:不删除
     * @param response
     * @param request
     */
    @GetMapping("/common/download")
    public void fileDownload(String filePath, String fileName, boolean del, HttpServletResponse response, HttpServletRequest request){
        boolean delete = true;
        try{
            if (!FileUtils.isValidFilename(fileName)){
                throw new Exception("文件名称(" + fileName + ")非法，不允许下载。 ");
            }
            String url = filePath + File.separator + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (del){
                FileUtils.deleteFile(filePath);
            }
        }catch (Exception e){
            log.error("下载文件失败", e);
        }
    }
}
